package org.apfloat.spi;

import org.apfloat.ApfloatContext;

/**
 * Class for generating filenames for temporary files.
 *
 * @version 1.0
 * @author Mikko Tommila
 */

public class FilenameGenerator
{
    /**
     * Create a new filename generator. The generated filenames will
     * point to the specified directory path. The base file name is a
     * sequential number. The specified suffix is appended to the
     * final file name.
     *
     * @param path The path where the file are created. If <code>null</code>, the default file path from the {@link ApfloatContext} is used.
     * @param initialValue The initial value for the numbers. If <code>null</code>, the default file initial value from the {@link ApfloatContext} is used.
     * @param suffix The suffix for file names. If <code>null</code>, the default file suffix from the {@link ApfloatContext} is used.
     *
     * @exception NumberFormatException If initialValue is not a valid integer number.
     */

    public FilenameGenerator(String path, String initialValue, String suffix)
        throws NumberFormatException
    {
        if (path == null)
        {
            ApfloatContext ctx = ApfloatContext.getContext();
            path = ctx.getProperty(ApfloatContext.FILE_PATH);
        }

        if (initialValue == null)
        {
            ApfloatContext ctx = ApfloatContext.getContext();
            initialValue = ctx.getProperty(ApfloatContext.FILE_INITIAL_VALUE);
        }

        if (suffix == null)
        {
            ApfloatContext ctx = ApfloatContext.getContext();
            suffix = ctx.getProperty(ApfloatContext.FILE_SUFFIX);
        }

        this.path = path;
        this.value = Long.parseLong(initialValue);
        this.suffix = suffix;
    }

    /**
     * Generate a filename. The returned filename is unique among
     * those generated by this filename generator.
     *
     * @return A generated file name.
     */

    public synchronized String generateFilename()
    {
        return this.path + (this.value++) + this.suffix;
    }

    /**
     * Returns the path setting of this filename generator.
     *
     * @return The path setting of this filename generator.
     */

    public String getPath()
    {
        return this.path;
    }

    /**
     * Returns the current initial value of the base file names generated.
     *
     * @return The current initial value of the base file names generated.
     */

    public synchronized String getInitialValue()
    {
        return String.valueOf(this.value);
    }

    /**
     * Returns the suffix setting of this filename generator.
     *
     * @return The suffix setting of this filename generator.
     */

    public String getSuffix()
    {
        return this.suffix;
    }

    private String path;
    private long value;
    private String suffix;
}
